package com.acme.bankapp.domain.account;

import com.acme.bankapp.exceptions.NotEnoughFundsException;
import com.acme.bankapp.exceptions.OverDraftLimitExceededException;

public class CheckingAccount extends AbstractAccount {

    private double overdraft;

    public CheckingAccount(final double amount, final double overdraft) throws IllegalArgumentException {
        super(amount);

        if (overdraft < 0) {
            throw new IllegalArgumentException("Not legal parameter for overdraft");
        }
        this.overdraft = overdraft;
    }

    public void withdraw(final double amount) throws NotEnoughFundsException {
        try {
            super.withdraw(amount);
        } catch (NotEnoughFundsException e) {
            if (this.maximumAmountWithDraw() < amount) {
                throw new OverDraftLimitExceededException(this);
            } else {
                overdraft -= amount - this.getBalance();
                this.setBalance(0);
            }
        }
    }

    @Override
    public double maximumAmountWithDraw() {
        return getBalance() + overdraft;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof CheckingAccount)) return false;
        if (!super.equals(o)) return false;

        CheckingAccount that = (CheckingAccount) o;

        return Double.compare(that.overdraft, overdraft) == 0;
    }

    @Override
    public int hashCode() {
        int result = super.hashCode();
        long temp;
        temp = Double.doubleToLongBits(overdraft);
        result = 31 * result + (int) (temp ^ (temp >>> 32));
        return result;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("c;").append(super.toString()).append("overdraft=").append(decimalValue()).append(';');
        return sb.toString();
    }

    @Override
    public long decimalValue() {
        return Math.round(this.overdraft);
    }
}
